package top.wshape1.shiziapi.gateway.filter;

import com.alibaba.fastjson2.JSON;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.Base64Utils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import top.wshape1.shiziapi.common.constant.AuthConstant;
import top.wshape1.shiziapi.common.domain.CommonUser;
import top.wshape1.shiziapi.gateway.config.ShiZiApiConfig;

import java.nio.charset.StandardCharsets;

/**
 * @author Wshape1
 * @version 1.0
 * @description 全局过滤器，拦截是否登录，优先级低于Security的WebFilter，经过Security校验通过来到这里
 * @since 2023-08-20
 */

@Slf4j
@Component
public class GatewayGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("AuthGlobalFilter 我来了");
        ServerHttpRequest request = exchange.getRequest();
//        ServerHttpResponse response = exchange.getResponse();
//        HttpHeaders headers = request.getHeaders();

        // 请求日志
//        log.info("请求唯一标识：" + request.getId());
        String path = request.getPath().value();
        log.info("请求路径：{baseUrl}" + path);
        log.info("请求方法：" + request.getMethod().name());
        log.info("请求参数：" + request.getQueryParams());
//        String sourceAddress = request.getLocalAddress().getHostString();
//        log.info("请求来源地址：" + sourceAddress);
//        log.info("请求来源地址：" + request.getRemoteAddress());


        CommonUser user = exchange.getAttribute("user");

        // 表示没有携带Token进来的，之间放行
        if (user == null) {
            return chain.filter(exchange);
        }

        String subject = JSON.toJSONString(user);
        // 将用户token的信息放置请求头 传递给下层请求
        ServerHttpRequest.Builder builder = request.mutate()
                .header(AuthConstant.HEADER_PAYLOAD_NAME, Base64Utils.encodeToString(subject.getBytes(StandardCharsets.UTF_8)));

        // 如果不是去uaa服务就把author头移除减少请求带宽
        // 因为懒得改UAA的过滤器，所以访问uaa还是要有Author头
        if (!(new AntPathMatcher().match("/api/uaa/**", path))) {
            builder.header(HttpHeaders.AUTHORIZATION, "");
        }

        return chain.filter(exchange.mutate()
                .request(builder.build())
                .build());
    }


    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE;
    }
}
